const superagent = require("superagent");
//require("superagent-proxy")(superagent);
let charset = require("superagent-charset");
let cheerio = require('cheerio');
let userAgent = require('../tools/userAgent');
const cookie = require('./cookie');

let cutText = (start, end, text) => {
    let tmp = text.substring(((start?text.indexOf(start):0)+ start.length));
    return tmp.substring(0, (end?tmp.indexOf(end):text.length));
     
}

/**
 * 
 */
let getCommentVersion = (itemId) => {
    //const proxy = "http://proxy.intra.panasonic.cn:8080";
    let _url = `https://detail.tmall.com/item.htm?id=${itemId}`;
    return new Promise((resolve, reject) => {
        try {
            charset(superagent)
                //superagent 
                .get(_url)
                //.proxy(proxy)
                .set("dataType", "text")
                .set({
                    Host: "detail.tmall.com",
                    "User-Agent":
                        "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0",
                    Accept: "*/*",
                    "Accept-Language":
                        "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                    "Accept-Encoding": "gzip, deflate, br",
                    Connection: "keep-alive",
                    // Connection: "close",
                    Cookie:
                        "t=f2ece3c010247a18fa0185942c46b90f; _tb_token_=ea6e0773e963f; cookie2=1b579ad6da721bba1523415252133928",
                    Pragma: "no-cache",
                    "Cache-Control": "no-cache"
                })
                .charset()
                .buffer(true)
                .end(function (err, res) {
                    try {
                        if (err) {
                            throw err;
                        }
                        if (!res || !res.text) {
                            throw new Error("获取不到 res/res.text");
                        }
                        //let $ = cheerio.load(res.text);
                        let TShopSetup = cutText('TShop.Setup(', ");", res.text);//截取这个函数对应的参数
                        let TShopSetup_parameter = JSON.parse(TShopSetup);
                        if (!TShopSetup_parameter.valItemInfo || !TShopSetup_parameter.valItemInfo.skuList || TShopSetup_parameter.valItemInfo.skuList.length == 0) {
                            throw `没有获取到skuList!!`
                        }
                        if (!TShopSetup_parameter.rateConfig) {
                            throw `没有获取到rateConfig!!`
                        }
                        let spuId = TShopSetup_parameter.valItemInfo
                        let result = {
                            skuList: TShopSetup_parameter.valItemInfo.skuList,
                            skuMap: TShopSetup_parameter.valItemInfo.skuMap,
                            propertyPics: TShopSetup_parameter.propertyPics,
                            rateConfig: {
                                itemId: TShopSetup_parameter.rateConfig.itemId,
                                sellerId: TShopSetup_parameter.rateConfig.sellerId,
                                spuId: TShopSetup_parameter.rateConfig.spuId
                            },
                            itemDO:{
                                reservePrice:TShopSetup_parameter.itemDO.reservePrice,
                                imgVedioPic:TShopSetup_parameter.itemDO.imgVedioPic,
                                prov:TShopSetup_parameter.itemDO.prov,
                                brand:TShopSetup_parameter.itemDO.brand,
                                brandId:TShopSetup_parameter.itemDO.brandId,
                                spuId:TShopSetup_parameter.itemDO.spuId,
                                categoryId:TShopSetup_parameter.itemDO.categoryId
                            },
                            rstShopId:TShopSetup_parameter.rstShopId,
                            propertyPics:TShopSetup_parameter.propertyPics
                        };
                        resolve(result);
                    }
                    catch (error) {
                        reject(error);
                    }
                });
        }
        catch (error) {
            reject(error);
        }
    });
}

let getCommentDetail = function (rateConfig) {
    let _config = {
        ...rateConfig,
            ...{
                order:1,
                append:0,
                content:1//有内容
            }
    };
    // let configStr =  Object.keys(_config).map(key=>{
    //     return `${key}=${_config[key].toString()}`;
    // }).join('&');
    let url = `https://rate.tmall.com/list_detail_rate.htm`;
    return new Promise((resolve, reject) => {
        try {
            charset(superagent)
                .get(url) //目标地址
                .query(_config)
                .set("dataType", "text")
                .set("Cookie", cookie)
                .set("User-Agent", userAgent.random())
                .set({
                    Host: "rate.tmall.com",
                    Accept: "*/*",
                    "Accept-Language":
                        "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                    "Accept-Encoding": "gzip, deflate, br",
                    Referer: `https://detail.tmall.com/item.htm?id=${rateConfig.itemId}`,
                    Connection: "keep-alive",
                    //Connection: "close",
                    Cookie:cookie,
                    TE: "Trailers",
                    "Cache-Control": "no-cache"
                })
                .charset()
                .buffer(true)
                .end(function (err, res) {
                    if (err) {
                        reject(err);
                        //throw err;
                    }
                    try {
                        let jsonStr = cutText('(',null,res.text);
                        if(jsonStr[jsonStr.length-1]==')'){
                            jsonStr = jsonStr.substring(0,jsonStr.length-1);
                        }
                        //console.log(jsonStr);
                        let json = JSON.parse(jsonStr);//避免json格式有误
                        resolve(json);
                    }
                    catch (error) {
                        reject(error);
                    }
                });
        }
        catch (error) {
            reject(error);
        }
    });
}
//偷懒直接用jd的fn名了
module.exports.getCommentVersion = getCommentVersion;
module.exports.getCommentDetail = getCommentDetail;


// const fs = require('fs');
// (async () => {
//     const itemId = '15385213226';
//     let rateConfig = {};
//     getCommentVersion(itemId).then(r => {
//         console.log(r);
//         rateConfig = r.rateConfig;
//         rateConfig.currentPage = 999999;
//         getCommentDetail(rateConfig).then(r => {
//             console.log(r);
//             fs.writeFileSync('./response.json',JSON.stringify(r));
//             if(!r.rateDetail){
//                 console.log('out!')
//             }
//         }).catch(error => { console.error(error) });
//     }).catch(error => { console.error(error) });  
// })();




